<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>文件上载演示</title>
    <script src="bower_components/jquery/dist/jquery.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/axios/0.21.1/axios.min.js"></script>
</head>
<body>
<form id="demoForm" method="post"
      enctype="multipart/form-data"
      action="/upload/file">
    <div>
        <label>上传文件
            <input id="imageFile" type="file" name="imageFile">
        </label>
    </div>
    <button type="submit">上传文件</button>
</form>
<img id="image" src="http://localhost:8899/a.png" alt="">
</body>
<script>
    //在id为demoForm的表单提交时运行这个方法
    $("#demoForm").submit(function () {
        //获得用户上传的文件
        let files = document.getElementById("imageFile").files;
        //判断是否选中了文件
        if (files.length > 0) {
            //执行上传的操作
            uploadFile(files[0]);
        } else {
            alert("选择上传文件")
        }
        //阻止表单提交以实现异步效果
        return false;
    })

    function uploadFile(file) {
        //创建表单
        let form = new FormData();
        form.append("imageFile", file);
        axios({
            url: "/upload/file",
            method: "post",
            data: form
        }).then(function (response) {
            console.log(response.data);
            //将上传图片显示用的url赋值给img标签的src属性
            $("#image").attr("src",response.data);
        })
    }
</script>
</html>